#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <cstdio>

//fun_t表示返回值void *，参数void *的函数指针
typedef void *(*fun_t)(void *);

//封装回调函数的参数
class ThreadData
{
public:
    void *args_;   //传入回调函数的参数
    std::string name_; //线程名字
};


//线程的封装
class Thread
{
public:
    //构造thread对象
    Thread(int num, fun_t callback, void *args) 
        : func_(callback)
    {
        //定义名字缓冲区
        char nameBuffer[64];
        //将名字格式化写入到缓冲区
        snprintf(nameBuffer, sizeof nameBuffer, "Thread-%d", num);
        //赋值线程名字
        name_ = nameBuffer;
        //赋值回调函数的参数
        tdata_.args_ = args;
        tdata_.name_ = name_;
    }
    //封装线程启动方法
    void start()
    {
        pthread_create(&tid_, nullptr, func_, (void*)&tdata_);
    }
    //封装线程等待方法
    void join()
    {
        pthread_join(tid_, nullptr);
    }
    //返回线程的名字
    std::string name()
    {
        return name_;
    }
    //析构线程对象
    ~Thread()
    {
    }

private:
    std::string name_;      //线程名字
    fun_t func_;            //线程启动的回调函数
    ThreadData tdata_;      //封装的回调函数的参数
    pthread_t tid_;         //线程id
};